package org.baizhiedu.factory;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;

/**
 * ClassName: ProxyBeanPostProcessor
 * Description:
 * Date: 2022/11/22 PM 3:19:40
 * <p>
 * project: spring5
 * package: org.baizhiedu.factory
 * email: 1085844536@qq.com
 * version:
 *
 * @author WangGuojian
 */
public class ProxyBeanPostProcessor implements BeanPostProcessor {

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }

    /**
     * Proxy.newProxyInstance();
     *
     * @param bean     bean
     * @param beanName id
     * @return bean object
     * @throws BeansException 异常
     */
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        InvocationHandler handler = (proxy, method, args) -> {
            System.out.println("--- new log ---");
            return method.invoke(bean, args);
        };

        return Proxy.newProxyInstance(ProxyBeanPostProcessor.class.getClassLoader(),
                bean.getClass().getInterfaces(), handler);
    }
}
